import { Selector } from 'antd-mobile'
import LineChart from '@/components/pageComponents/home/chartPage/charts/LineChart'
import PieChart from '@/components/pageComponents/home/chartPage/charts/PieChart'
import RowBarChart from '@/components/pageComponents/home/chartPage/charts/RowBarChart'
import { cFetch } from '@/lib/Http'
import {useState, useMemo, useEffect} from 'react'
import dayjs from 'dayjs'

type lineItem = { happen_at: string; amount: number }
type lineChartData = lineItem[]
type pieItem = { tag_id: number; amount: number; tag: Tag }
type pieChartData = pieItem[]

export default function ChartGroup(props:{
  timePeriod: { happened_after: string; happened_before: string }
}){
  const [kindArr, setKindArr] = useState(['expenses'])
  const [lineData, setLineData] = useState<{ groups: lineChartData; total: number }>({
    groups: [],
    total: 0
  })
  const [pieData, setPieData] = useState<{ groups: pieChartData; total: number }>({
    groups: [],
    total: 0
  })
  const options = [
    { label: '支出', value: 'expenses' },
    { label: '收入', value: 'income' }
  ]
  const finalChartData1 = useMemo<[string, number][]>(() => {
    if (!props.timePeriod.happened_after || !props.timePeriod.happened_before) {
      return []
    }
    const start = dayjs(props.timePeriod.happened_after)
    const end = dayjs(props.timePeriod.happened_before)
    const diff = end.diff(start, 'day') + 1
    return Array.from({ length: diff }, (v, i) => {
      const date = start.add(i, 'day').format('YYYY-MM-DD')
      const item = lineData.groups.find((item) => item.happen_at === date)
      return [date, item?.amount || 0]
    })
  },[lineData])
  const finalChartData2 = useMemo<{ name: string; value: number }[]>(() => {
    return pieData.groups.map((ele) => ({
      name: ele.tag.name,
      value: ele.amount
    }))
  },[pieData])
  const finalChartData3 = useMemo<{tag: Tag,amount: number,percent: number}[]>(() => {
    const total = pieData.groups.reduce((acc, cur) => acc + cur.amount, 0)
    return pieData.groups.map((ele) => ({
      ...ele,
      percent: Math.round(ele.amount / total * 100)
    }))
  },[pieData])
  const fetchFn = async <K extends 'happen_at' | 'tag_id'>(groupBy: K) => {
    type rData<K> = K extends 'happen_at'
      ? { groups: lineChartData; total: number }
      : { groups: pieChartData; total: number }
    return await cFetch.get<rData<K>>(
      '/item/list/summary',
      {
        ...props.timePeriod,
        group_by: groupBy,
        kind: kindArr[0]
      },
      {
        _autoLoading: true
      }
    )
  }
  useEffect(() => {
    if (props.timePeriod.happened_after && props.timePeriod.happened_before) {
      getData()
    }
  },[kindArr, props.timePeriod.happened_after, props.timePeriod.happened_before])
  const getData = async () => {
    const [lineData, pieData] = await Promise.all([
      fetchFn('happen_at'),
      fetchFn('tag_id')
    ])
    setLineData(lineData)
    setPieData(pieData)
  }
  const getAllDataByKind = async (arr: string[]) => {
    if(arr.length){
      setKindArr(arr)
    }
  }
  return <div className="chartGroupWrap h-full overflow-y-auto">
    <Selector
      options={options}
      columns={2}
      value={kindArr}
      onChange={ arr => getAllDataByKind(arr)}
      className='p-2'
    />
    <LineChart data={finalChartData1}/>
    <PieChart data={finalChartData2}/>
    <RowBarChart data={finalChartData3}/>
  </div>
}